<?php defined('SYSPATH') or die('No direct script access.');

class Model_Shop_Review
{ 
    const REVIEWS_PER_PAGE = 10;
    public static $available_sort = array('usefulness', 'date'); 
    
    public static function get_reviews(Model_Shop $shop, $page = null, $get_count = false, $order_by = 'usefulness')
    {                
        if (!$order_by) {
            $order_by = 'usefulness';
        }
        if (!in_array($order_by, self::$available_sort) ) {
            throw new Model_Exception('Некорректное поле для сортировки');    
        }
        
        if ($reviews = Cache::instance()->get('reviews_'.$shop->id.'_'.$page.'_'.$get_count.'_'.$order_by)) {
            return $reviews;
        } 
             
        /*$query = DB::select()->from(
                    array(ORM::factory('review_yandexmarket')->get_reviews_query($entity)
                    ->union(ORM::factory('review_rozetka')->get_reviews_query($entity)), 'table')
                ); */
        $query = ORM::factory('shop_review_irecommend')->get_reviews_query($shop); 
            
        if ($page) {
            $count = self::get_reviews_per_page();
            $offset = ($page - 1) * $count;
            $query->offset($offset)->limit($count);    
        }
        
        if ($order_by) {
            $query->order_by($order_by, 'DESC');   
        }
        
        $query = ORM::factory('shop_review_otzovik')->get_reviews_query($shop)
            ->union($query);
        
        if ($get_count) {
            /*$count = $query->select(array(DB::expr('COUNT(*)'), 'count'))->execute()->as_array();
            $count = $count[0]['count'];
            Cache::instance()->set('reviews_'.$model_id.'_'.$page.'_'.$get_count.'_'.$order_by, $count); 
            return $count;   */
        }
        $reviews = $query
                    ->execute()
                    ->as_array();
        Cache::instance()->set('reviews_'.$shop->id.'_'.$page.'_'.$get_count.'_'.$order_by, $reviews); 
        return $reviews;       
    }
    
    public static function get_reviews_per_page()
    {
        return self::REVIEWS_PER_PAGE;
    }
}